package com.tjl.foodapp;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.tjl.foodapp.utils.SettlePopup;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CartFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public CartFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FoodListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CartFragment newInstance(String param1, String param2) {
        CartFragment fragment = new CartFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    //页面元素
    ImageButton btn_back_head,btn_like_head;
    TextView tx_shopname_head;
    RecyclerView rv_foodlist_center;
    //上下文
    Context context;
//结账弹窗
    BasePopupView addOrderDialog;
    //请求队列
    RequestQueue queue;
    //子页面管理器
    FragmentManager manager;
    // 数据源
    List<Food> list = new ArrayList<Food>();
    int shop_id =0;
    //店铺ID
    //前一页面
    String prePage = "";
    //结账按钮
    Button btn_settle;
    //总价
    TextView all_price;
    //适配器类
    class MyAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =  LayoutInflater.from(context).inflate(R.layout.food_item_cart,null);
            return new CartFragment.MyAdaper.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            CartFragment.MyAdaper.ViewHolder viewHolder = (CartFragment.MyAdaper.ViewHolder)holder;
            Food food = list.get(position);
            viewHolder.tx_foodname_price_fooditem.setText(food.getFoodname()+" "+food.getPrice()+"元");
            viewHolder.tx_intro_fooditem.setText(food.getIntro());

            getImageByURL(Utils.urlBase+"image/"+food.getPic()+".jpg"
                    ,viewHolder.img_food_fooditem);
//            viewHolder.img_food_fooditem.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("shop_id",shop_id);
//                    bundle.putInt("food_id",food.getFood_id());
//                    bundle.putString("prePage","foodlist");
//                    changeFragment(new FoodDetailFragment(),bundle,"fooddetail");
//                }
//            });
            Map<Integer, Integer> map = MainActivity.cart.get(shop_id);
            viewHolder.tx_num.setText("购买数量:" + map.get(food.getFood_id()));
            viewHolder.tx_zongjia.setText("小计:" + map.get(food.getFood_id())*food.getPrice()+"元");
            //删除购物车中的一项
            viewHolder.btn_delete_fooditem.setOnClickListener(v -> {
                new XPopup.Builder(getContext()).asConfirm("确认移除该商品", "",
                        () -> {
                            MainActivity.cart.get(shop_id).remove(food.getFood_id());
                            list.remove(position);
                            //修改本地存储
                            SharedPreferences.Editor edit = MainActivity.sp.edit();
                            edit.putString("cart_json_" + MainActivity.user_id,new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(MainActivity.cart));
                            edit.commit();
                            notifyDataSetChanged();
                            //修改总价
                            double allPrice = 0;
                            Map<Integer, Integer> shopCart = MainActivity.cart.get(shop_id);
                            for (Food f : list){
                                if (shopCart.containsKey(f.getFood_id())){
                                    allPrice += f.getPrice() * shopCart.get(f.getFood_id());
                                }
                            }
                            all_price.setText("总价:"+allPrice+"元");
                        }).show();


            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder{
            ImageButton img_food_fooditem;
            TextView tx_foodname_price_fooditem;
            TextView tx_intro_fooditem;
            TextView tx_num,tx_zongjia;
            Button btn_delete_fooditem;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                img_food_fooditem = itemView.findViewById(R.id.img_food_fooditem);
                tx_foodname_price_fooditem = itemView.findViewById(R.id.tx_foodname_price_fooditem);
                tx_intro_fooditem = itemView.findViewById(R.id.tx_intro_fooditem);
                tx_num = itemView.findViewById(R.id.tx_num);
                tx_zongjia = itemView.findViewById(R.id.tx_zongjia);
                btn_delete_fooditem = itemView.findViewById(R.id.btn_delete_fooditem);

            }
        }
    }
    CartFragment.MyAdaper adaper;
    User user;
    String shopname;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cart, container, false);
        btn_back_head = view.findViewById(R.id.btn_back_head);
        tx_shopname_head = view.findViewById(R.id.tx_shopname_head);
        rv_foodlist_center = view.findViewById(R.id.rv_foodlist_center);
        btn_settle = view.findViewById(R.id.btn_settle);
        all_price = view.findViewById(R.id.all_price);
        context = this.getActivity();
        queue = Volley.newRequestQueue(context);
        manager = this.getActivity().getSupportFragmentManager();
        adaper = new CartFragment.MyAdaper();
        rv_foodlist_center.setAdapter(adaper);
        rv_foodlist_center.setLayoutManager(new LinearLayoutManager(context));
        //获取前一个页面传递的参数
        shop_id =  this.getArguments().getInt("shop_id");
        shopname = this.getArguments().getString("shopname");
        prePage = this.getArguments().getString("prePage");
        tx_shopname_head.setText(shopname);
        getArrayList(Utils.urlBase+"and_getFoodsByShopId.do?id="+shop_id);
        //获取用户信息
        getJSONObject(Utils.urlBase+"and_getUserByUserId.do?id="+MainActivity.user_id,"user",null);
        //设置返回按钮的点击事件
        btn_back_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(prePage.equals("shoplist")||prePage.equals("fooddetail")){
                    changeFragment(new ShopListFragment(),null,"shoplist");
                } else if(prePage.equals("shopcollect")) {
                    Bundle bundle = new Bundle();
                    bundle.putString("page","shop");
                    changeFragment(new CollectFragment(), bundle, "collectshop");
                } else if (prePage.equals("foodlist")) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("shop_id",shop_id);
                    bundle.putString("shopname", shopname);
                    bundle.putString("prePage","shoplist");
                    changeFragment(new FoodListFragment(), bundle, "foodList");
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("page","shop");
                    changeFragment(new ShopListFragment(), bundle, "shoplist");
                }
            }
        });

        //设置结账按钮的点击事件
        btn_settle.setOnClickListener(v -> {

            if (MainActivity.cart.get(shop_id).size() == 0){
                Toast.makeText(context,"购物车为空",Toast.LENGTH_SHORT).show();
                return;
            }

            addOrderDialog = new XPopup.Builder(getContext())
                    .asCustom(new SettlePopup(getContext(), time -> {
                        //提交逻辑
                        for (Food food : list) {
                            Integer num = MainActivity.cart.get(shop_id).get(food.getFood_id());
                            Order order = new Order(0,
                                    MainActivity.user_id,
                                    user.getUsername(),
                                    food.getFood_id(),
                                    food.getFoodname(),
                                    num,
                                    num * food.getPrice(),
                                    new Date(),
                                    time,
                                    null,
                                    null);
                            try {
                                JSONObject obj = new JSONObject(new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(order));
                                //处理ordertime字段 转换成yyyy-MM-dd格式
                                obj.put("ordertime", DateUtil.now());
                                getJSONObject(Utils.urlBase + "and_addOrder.do", "order", obj);

                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    })).show();
        });

        return view;
    }
    //获取网络图片
    public void getImageByURL(String url,ImageButton imageButton){
        int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
        int cachSize = maxMemory/8;
        LruCache<String, Bitmap> lruCache = new LruCache<String,Bitmap>(cachSize);
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String s) {
                return lruCache.get(s);
            }

            @Override
            public void putBitmap(String s, Bitmap bitmap) {
                lruCache.put(s,bitmap);
            }
        };
        ImageLoader loader = new ImageLoader(queue,imageCache);
        ImageLoader.ImageListener listener
                = ImageLoader.getImageListener(imageButton,
                R.drawable.ic_launcher_background,
                R.drawable.ic_launcher_foreground);
        loader.get(url,listener);
    }
    //获取网络数据
    public void getArrayList(String url){
        Response.Listener listener1 = new Response.Listener(){

            @Override
            public void onResponse(Object o) {
                ArrayList<Food> list2 = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),new TypeToken<ArrayList<Food>>(){}.getType());
                //过滤 只有在购物车中的才能出现
                if (MainActivity.cart.get(shop_id) == null){
                    return;
                }else{
                    Map<Integer, Integer> map = MainActivity.cart.get(shop_id);
                    System.out.println("123:" + map);
                    list2.stream().forEach(System.out::println);
                    if (map.containsKey(3)){
                        System.out.println(123);
                    }
                    list = list2.stream().filter(food -> map.containsKey(food.getFood_id()))
                            .collect(Collectors.toList());
                    //设置总价
                    Map<Integer, Integer> shopCart = MainActivity.cart.get(shop_id);
                    double all = 0;
                    for (Food food : list){
                        if (shopCart.containsKey(food.getFood_id())){
                            all += food.getPrice() * shopCart.get(food.getFood_id());
                        }
                    }
                    all_price.setText("总价:" + all + "元");
                }
                adaper.notifyDataSetChanged();
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonArrayRequest(url,listener1,listener2);
        queue.add(request);
    }
    public void changeFragment(Fragment fragment,Bundle bundle,String tag){
        //清空子页面栈
        for(int i=0,count = manager.getBackStackEntryCount();i<count;i++){
            manager.popBackStack();
        }
        //创建一个子页面的事务，以便切换子页面
        FragmentTransaction transaction = manager.beginTransaction();
        //设置子页面的初始化参数
        fragment.setArguments(bundle);
        //切换子页面，让子页面显示到主页面的指定位置
        transaction.add(R.id.linear_fragment,fragment);
        //给栈中的子页面一个标签
        transaction.addToBackStack(tag);
        //提交事务
        transaction.commit();
    }
    public void getJSONObject(String url,String type,JSONObject object){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                //如果是添加订单请求 关闭弹窗
                if (url.contains(Utils.urlBase+"and_addOrder.do") && addOrderDialog != null){
                    addOrderDialog.dismiss();
                }
                if(type.equals("food")) {

                }
                else if(type.equals("user")) {
                    user = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(), User.class);

                }
                else if(type.equals("order")){
                    String result = "网络连接错误";
                    try {
                        JSONObject obj = new JSONObject(o.toString());
                        result = obj.getString("msg");
                        if (obj.getBoolean("flag")){
                            // 清空map
                            MainActivity.cart.remove(shop_id);
                            list = new ArrayList<>();
                            adaper.notifyDataSetChanged();
                            SharedPreferences.Editor edit = MainActivity.sp.edit();
                            edit.putString("cart_json",new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(MainActivity.cart));
                            edit.commit();

                            //退回上一页
                            Bundle bundle = new Bundle();
                            bundle.putInt("shop_id",shop_id);
                            bundle.putString("shopname",shopname);
                            bundle.putString("prePage","shoplist");
                            changeFragment(new FoodListFragment(),bundle,"foodlist");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(context,result,Toast.LENGTH_LONG).show();
                }

            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,object,listener1,listener2);
        queue.add(request);
    }
    public void sendJSONObject(String url,Collect collect)  {
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String msg = jsonObject.getString("msg");
                    Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(collect,Collect.class);
        try {
            JSONObject object = new JSONObject(s);
            JsonRequest request = new JsonObjectRequest(url,object,listener1,listener2);
            queue.add(request);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

}